package com.yunshipei.core.download;

import android.content.Context;
import android.net.Uri;
import android.os.Process;
import android.text.TextUtils;
import android.util.Log;
import android.webkit.MimeTypeMap;
import android.webkit.URLUtil;

import com.yunshipei.core.model.XDownloadModel;
import com.yunshipei.core.utils.YspLogUtils;

import org.xwalk.core.XWalkCookieManager;
import org.xwalk.core.XWalkDownloadListener;

public class TabDownloadListener extends XWalkDownloadListener {

    private XWalkCookieManager cookieManager = new XWalkCookieManager();

    private XWalkDownloadListenerCallback xWalkDownloadListenerCallback;

    public TabDownloadListener(Context context, XWalkDownloadListenerCallback callback) {
        super(context);
        this.xWalkDownloadListenerCallback = callback;
    }

    @Override
    public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
        String fileName = getFileName(url, contentDisposition, mimetype);
        Uri src = Uri.parse(url);
        if (src != null && (src.getScheme().equals("http") || src.getScheme().equals("https")) && xWalkDownloadListenerCallback != null) {
            String tempFileName = src.getQueryParameter("_ysp_attachment_fileName");
            if (!TextUtils.isEmpty(tempFileName)) {
                fileName = tempFileName;
            }
            String log = fileName + "\n" + url + "\n" + userAgent + "\n" + contentDisposition + "\n" + mimetype + "\n" + contentLength;
            Log.d("_download", log);
            YspLogUtils.d(log);
            XDownloadModel downloadModel = new XDownloadModel(url, contentDisposition, cookieManager.getCookie(url), contentLength, fileName, userAgent);
            Log.d("_download_model", "process:" + Process.myPid() + "\n" + downloadModel.toString());
            YspLogUtils.d("process:" + Process.myPid() + "\n" + downloadModel.toString());
            xWalkDownloadListenerCallback.yspDownload(url, downloadModel);
        }
    }

    public interface XWalkDownloadListenerCallback {
        void yspDownload(String fromUrl, XDownloadModel xDownloadModel);
    }

    private String getFileName(String url, String contentDisposition, String mimetype) {
        String fileName = URLUtil.guessFileName(url, contentDisposition, mimetype);
        int extensionIndex = fileName.lastIndexOf(".");
        String extension = null;
        if ((extensionIndex > 1) && (extensionIndex < fileName.length())) {
            extension = fileName.substring(extensionIndex + 1);
        }

        // If the file name does not have a file extension, append extension based on MIME type.
        if (extension == null) {
            extension = MimeTypeMap.getSingleton().getExtensionFromMimeType(mimetype);
            if (extension != null) fileName = fileName + "." + extension;
        }
        return fileName;
    }
}
